package com.tg.app.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.demo.view.PtzDirectionView;
import com.demo.view.PtzView;
import com.demo.view.TGBottomSheetDialog;
import com.tange.base.toolkit.DimenUtil;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.R;
import com.tg.app.activity.device.CameraViewActivity;
import com.tg.app.adapter.PrePositionAdapter;
import com.tg.app.adapter.PrePositionDialogAdapter;
import com.tg.app.bean.DevicePresetPoints;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.camera.CameraHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.appcommon.android.TGLog;
import com.tg.data.media.OnICameraListener;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.appcommon.android.ImageUtils;
import com.tg.appcommon.android.LanguageUtils;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;


import java.util.List;
import java.util.Objects;

public class PrePositionDialog extends TGBottomSheetDialog implements OnICameraListener, PrePositionAdapter.PrePositionListener{
    private PrePositionAdapter adapter;
    private Bitmap bitmap;
    private Camera camera;
    private AVIOCTRLDEFs.Tcis_SetPtzPosReq ptzPos;
    private short pspType;
    private PtzView ptzControlView;
    private ImageView delImage;
    private TextView delCancel, delSubmit;
    @Override
    public void updateDelStatus() {
        if (adapter.isEditEnable()) {
            if (adapter.getSelectedPresetPoints().size() > 0) {
                delCancel.setVisibility(View.GONE);
                delSubmit.setVisibility(View.VISIBLE);
            } else {
                delSubmit.setVisibility(View.GONE);
                delCancel.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setSendPTZCmd(boolean isSend){
        if (ptzControlView != null){
            ptzControlView.setSendPTZCmd(isSend);
        }
    }

    @Override
    public void click(int position) {
        if (camera.isConnected()){
            createDialog();
        }else {
            TGToast.showToast(R.string.camera_send_failed);
        }
    }


    public void setCamera(@NonNull Camera camera) {
        this.camera = camera;
        camera.registerICameraListener(this);
        adapter.setData(camera.uid);
        adapter.setCamera(camera);
        if (camera.isConnected()){
            CameraHelper.getPspCMD(camera);
        }
    }

    @Override
    protected int getContentView() {
        return R.layout.layout_pre_position;
    }


    @Override
    protected void initView(@NonNull View view) {
        delImage = view.findViewById(R.id.bottom_sheet_pre_position_del_btn);
        delCancel = view.findViewById(R.id.bottom_sheet_pre_position_del_cancel);
        delSubmit = view.findViewById(R.id.bottom_sheet_pre_position_del_submit);

        PtzControlView ptz = view.findViewById(R.id.pre_position_control);
        PtzDirectionView ptz1 = view.findViewById(R.id.ptz_horizontal_control);
        PtzDirectionView ptz2 = view.findViewById(R.id.ptz_vertical_control);

        if (this.object instanceof DeviceFeature){
            DeviceFeature deviceFeature = (DeviceFeature) this.object;
            if (DeviceFeatureHelper.vertOnly(deviceFeature)) {
                ptzControlView = ptz2;
            } else if (DeviceFeatureHelper.horZOnly(deviceFeature)) {
                ptzControlView = ptz1;
            } else {
                ptzControlView = ptz;
            }
            ptzControlView.setClickable(true);
        }else{
            ptzControlView = ptz;
            ptzControlView.setClickable(true);
            ptzControlView.setImageView(R.mipmap.ic_tange_switch_ptz);
        }

        ptzControlView.setVisibility(View.VISIBLE);
        bottomSheetDialog.setContentView(view);

        RecyclerViewGridLayoutManager gridLayoutManager = new RecyclerViewGridLayoutManager(context, 3);
        RecyclerView recyclerView = view.findViewById(R.id.pre_position_recyclerview);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(CommItemDecoration.createVertical(Color.TRANSPARENT, DimenUtil.dp2px(context, 10)));
        recyclerView.addItemDecoration(CommItemDecoration.createHorizontal(Color.TRANSPARENT, DimenUtil.dp2px(context, 10)));
        ((DefaultItemAnimator) Objects.requireNonNull(recyclerView.getItemAnimator())).setSupportsChangeAnimations(false);
        bottomSheetDialog.setContentView(view);
        Objects.requireNonNull(bottomSheetDialog.getWindow()).setDimAmount(0f);
        adapter = new PrePositionDialogAdapter(context, this);
        recyclerView.setAdapter(adapter);
        view.findViewById(R.id.bottom_sheet_pre_position_back).setOnClickListener(v -> bottomSheetDialog.dismiss());
        setListener();
    }

    public PrePositionDialog(@NonNull Context context, DeviceFeature deviceFeature, @NonNull DialogInterface.OnDismissListener onDismissListener) {
        super(context, null, deviceFeature);
        bottomSheetDialog.setOnDismissListener(onDismissListener);
    }

    private void setListener() {
        delImage.setOnClickListener(v -> {
            if (adapter.getPrePositions().size() == 0) return;
            delCancel.setVisibility(View.VISIBLE);
            delImage.setVisibility(View.GONE);
            adapter.setEditEnable(true);
            adapter.clearSelectedPresetPoints();
        });
        delCancel.setOnClickListener(v -> {
            delImage.setVisibility(View.VISIBLE);
            setDelCancel();
        });
        delSubmit.setOnClickListener(v -> {
            if (!camera.isConnected()){
                TGToast.showToast(R.string.camera_send_failed);
                return;
            }
            CameraHelper.deletedPresetPoints(camera, pspType, adapter.getSelectedPresetPoints());
        });
    }

    private void setDelCancel() {
        delCancel.setVisibility(View.GONE);
        adapter.setEditEnable(false);
        ptzControlView.setVisibility(View.VISIBLE);
    }



    public void show() {
        if (bottomSheetDialog.isShowing()) {
            bottomSheetDialog.dismiss();
        }
        bottomSheetDialog.show();
        ConstraintLayout layout = bottomSheetDialog.findViewById(R.id.pre_position_layout);
        if (layout != null) {
            BottomSheetBehavior bottomSheetBehavior =   BottomSheetBehavior.from(((View)layout.getParent()));
            Resources resources = bottomSheetDialog.getContext().getResources();
            int h = (int) resources.getDimension(R.dimen.player_height);
            int heightPixels = resources.getDisplayMetrics().heightPixels;
            int statusBarHeight = (int) Math.ceil(25 * bottomSheetDialog.getContext().getResources().getDisplayMetrics().density);
            int peekHight =  heightPixels - h;
            bottomSheetBehavior.setHideable(false);
            bottomSheetBehavior.setPeekHeight( peekHight);
            ViewGroup.LayoutParams layoutParams = layout.getLayoutParams();
            if (layoutParams != null) {
                layoutParams.height = peekHight;
                layout.setLayoutParams(layoutParams);
            }
        }
    }

    public void dismiss() {
        if (bottomSheetDialog.isShowing()) {
            bottomSheetDialog.dismiss();
        }
    }

    @Override
    public void receiveUpdateConnectStates(int state) {

        if (context instanceof  CameraViewActivity){
            CameraViewActivity cameraViewActivity = (CameraViewActivity) context;
            cameraViewActivity.receiveUpdateConnectStates(state);
        }
    }

    public void setOnPtzControlTouchListener(@NonNull PtzControlView.OnPtzControlTouchListener onPtzControlTouchListener) {
        ptzControlView.setOnPtzControlTouchListener(onPtzControlTouchListener);
    }

    private void getPresetPointsResp(byte[] data) {
        List<DevicePresetPoints> list = CameraHelper.getPresetPointsResp(data,false);
        for (DevicePresetPoints l:list){
            l.uuid = camera.uid;
        }
        adapter.setData(list);
        ObjectBoxUtil.saveDevicePresetPoints(list,camera.uid);
        adapter.setEditEnable(false);
        if (adapter.getPrePositions().size() == 0) {
            setDelCancel();
            delImage.setVisibility(View.GONE);
        } else {
            delImage.setVisibility(View.VISIBLE);
            ptzControlView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void receiveIOCtrlData(int type, @NonNull byte[] data) {
        if (type == AVIOCTRLDEFs.TCI_CMD_GET_PSP_RESP) {
            pspType = CameraHelper.getPresetPointsTypeResp(data);
            TGThreadPool.executeOnUiThread(() -> getPresetPointsResp(data));
        } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PTZ_POS_RESP) {
            ptzPos = CameraHelper.getPtzPosResp(data);

        } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
            int command = CameraHelper.getSetCommand(data);
            int result = CameraHelper.getSetCommandResult(data);
            if (command == AVIOCTRLDEFs.TCI_CMD_SET_PSP) {
                TGToast.showToast(result == 0 ? R.string.camera_send_completed : R.string.camera_send_failed);

                TGLog.d("PrePositionAdapter", "command == AVIOCTRLDEFs.TCI_CMD_SET_PSP");
                CameraHelper.getPspCMD(camera);
                TGThreadPool.executeOnUiThread(() -> delResp(result));
            }
        }
    }

    private void delResp(int result) {
        if (result == 0 && adapter.isEditEnable()) {
            delCancel.setVisibility(View.GONE);
            delSubmit.setVisibility(View.GONE);
            ptzControlView.setVisibility(View.VISIBLE);
            if (adapter.getPrePositions().size() == adapter.getSelectedPresetPoints().size()) {
                delImage.setVisibility(View.GONE);
            } else {
                delImage.setVisibility(View.VISIBLE);
            }
            adapter.clearSelectedPresetPoints();
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private void createDialog() {
        CameraHelper.getPtzPosCMD(camera);
        PrePositionCreateDialog dialog = new PrePositionCreateDialog(context).builder(adapter.getMode());
        String c = LanguageUtils.getLanguage(context);
        int num = adapter.getPrePositions().size() + 1;
        if (StringUtils.equalsIgnoreCase(adapter.getMode(), PrePositionAdapter.MODE_SWITCH)){
            num = adapter.getNewNum();
        }

        String name = context.getResources().getString(R.string.message_play_address) + num;
        if (!StringUtils.isEmpty(c) && c.equals(LanguageUtils.ZH_CN)) {
            name = String.valueOf(num);
        }

        dialog.setEditText(name);
        if (context instanceof CameraViewActivity) {
            CameraViewActivity activity = (CameraViewActivity) context;
            bitmap = activity.getPlayerView().getTextureViewBmp();
            if (bitmap != null) {
                dialog.setImageBitmap(bitmap);
            }
        }
        dialog.setListener(text -> {
            if(camera.isConnected()){
                DevicePresetPoints prePosition = new DevicePresetPoints();
                prePosition.name = text;
                prePosition.pos = ptzPos;
                prePosition.num = adapter.getNewNum();

                TGLog.d("PrePositionAdapter", "add  prePosition.num ==== " +  prePosition.num);
                if (ptzPos!=null){
                    prePosition.x = ptzPos.x;
                    prePosition.y = ptzPos.y;
                    prePosition.z = ptzPos.z;
                }
                prePosition.uuid = camera.uid;
                adapter.addData(prePosition);

                adapter.saveImage(ImageUtils.ImageCrop(bitmap, false), prePosition);
                adapter.notifyDataSetChanged();
                TGLog.d("PrePositionAdapter", "pspType ==== " + pspType);
                CameraHelper.setPresetPoints(camera, pspType, prePosition);
                ObjectBoxUtil.saveDevicePresetPoints(adapter.getPrePositions(),camera.uid);
            }else {
                TGToast.showToast(R.string.camera_send_failed);
            }
        });

        dialog.show();
    }


    public static class RecyclerViewGridLayoutManager extends GridLayoutManager {

        public RecyclerViewGridLayoutManager(@NonNull Context context, int spanCount) {
            super(context, spanCount);
        }

        @Override
        public void onLayoutChildren(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state) {
            try {
                //try catch一下
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }

        }
    }


}
